<?php

$user_obj = new user_obj();
$client_obj = new client_obj();

if (isset($_REQUEST['action'])){
    switch ($_REQUEST['action']) {
        case 'add_user':
            $user = $_REQUEST['user'];
            $user['password'] = md5($user['password']);
            $associatedClients = array();
            if ($user['userlevel']==USER_TYPE_CLIENT && !empty($user['associatedClients'])){
                foreach ($user['associatedClients'] as $key => $clientId) {
                    $associatedClients[$clientId] = $clientId;
                }
            }
            $associatedClients[$user['client']] = $user['client'];
            unset($user['associatedClients']);
            $newId = $user_obj->addUser($user);
            if (error_obj::isError($newId)){
                error_obj::setError($newId, UNEXCEPTED);
            } else {
                foreach ($associatedClients as $k => $clientId) {
                    $in_data = array();
                    $in_data['user_id'] = $newId;
                    $in_data['client_id'] = $clientId;
                    $result = $user_obj->addAssociatedClient($in_data);
                }
                base_obj::redirect(ROOT . '?input=list_of_users');
            }
            
            break;
    }
}

$filter = array();
$filter['active'] = 0;
if ($_SESSION['user']['profile']['userlevel'] == USER_TYPE_CLIENT) {
    $filter['clients'] = $_SESSION['user']['clients'];
}
$user['clients'] = $client_obj->getAllClients('contactPerson, klient_id, name, bad_payer', $filter, 'name ASC');

$user['userLevels'] = $GLOBALS['userLevels'];

$GLOBALS['template_data'] = $user;
?>
